home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: How to check array lenght?
- Date: Sat, 24 Feb 96 20:12:23 GMT
- Organization: none
- Message-ID: <825192743snz@genesis.demon.co.uk>
- References: <4gbphl$ht@malakor.kku.ac.th> <Pine.A32.3.91.960221002504.156335H-100000@black.weeg.uiowa.edu> <4ggmfs$tg@dopey.magg.net>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <4ggmfs$tg@dopey.magg.net> n4mwd@magg.net "Dennis Hawkins" writes:
-
- >The Amorphous Mass <robinson@blue.weeg.uiowa.edu> wrote:
- >
- >>On 20 Feb 1996, terdthai tong-un wrote:
- >
- >>> In subroutine that recieve pointer of array.
- >>> How to check number of multidimention array in that routine?
- >
- >> You can't. That information would have to be passed to the function
- >>via extra parameters or some other means.
- >Try using:
- >
- >#define numelem(array) (sizeof(array) / sizeof(array[0]))
- >
- >then pass the results as an extra parameter to your function.
-
- To see why this is necessary consider:
-
- void foo(int array[])
- {
- int i;
-
- printf("%lu\n", (unsigned long) sizeof array);
-
- array = &i;
- }
-
- By the rewrite rule for function parameters the prototype is treated exactly
- as it it were written as:
-
- void foo(int *array)
-
- So the value that gets printed is always the value of sizeof(int *) however
- the function was called. Although array looks like an array according to its
- declaration it is truely a pointer and behaves precisely like one (e.g.
- you can assign to it as in the example).
-
- Your define is good when simply passed an array name. However it could
- be improved simply to cope with any array-valued expression:
-
- #define numelem(array) (sizeof(array) / sizeof((array)[0]))
-
- or
-
- #define numelem(array) (sizeof(array) / sizeof *(array))
-
- which has the benefit of being able to correctly reject a type as the
- macro argument.
-
- These are safe against expressions with side-effects since sizeof doesn't
- evaluate its operand.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-